package com.simple.core.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.io.Serializable;
import java.util.List;

/**
 * Feed流查询Dao，主要使用findAll函数
 *
 * @author FanXing
 * @date 2023年03月03日 16:37
 */
public class SimpleSliceJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {

    public SimpleSliceJpaRepository(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
    }

    @Override
    protected <S extends T> Page<S> readPage(TypedQuery<S> query, Class<S> domainClass, Pageable pageable, Specification<S> spec) {
        if (pageable.isPaged()) {
            query.setFirstResult((int) pageable.getOffset());
            query.setMaxResults(pageable.getPageSize());
        }
        final List<S> content = query.getResultList();
        return new PageImpl<>(content, pageable, content.size());
    }
}
